﻿// ActionScript file
package {
	import com.electrotank.electroserver5.ElectroServer;
	import com.electrotank.electroserver5.api.*;
	import com.electrotank.electroserver5.user.User;
	import com.electrotank.electroserver5.user.UserManager;
	import com.electrotank.electroserver5.zone.Room;
	import com.electrotank.electroserver5.zone.Zone;
	
	import fl.data.DataProvider;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import lobby.LobbyEvent;

	public class LobbyManager extends  MovieClip{
		public var _lobby;
		private var _es:ElectroServer;
		private var _user:User;
		private var _myUserManager:UserManager;
		private var _room:Room = null;
		private var _currentSelectGame:String = null;
		private var _buddyList:EsObject = null;
		private var _myInfo:EsObject = null;
		private var _currentCheckUser:String = null;
		
		private var _gameListRefreshTimer:Timer;
		
		public var _gameRoom:Room = null;
		
		private static var userListState:String;
		
		
		
		public function LobbyManager(){
			
		}
		
		public function init(){
			trace("lobbmanager----1");
			_lobby.addEventListener(LobbyEvent.BUDDYLIST,loadBuddies);
			trace("lobbmanager----2");
			_lobby.addEventListener(LobbyEvent.CURRENTLIST,loadCurrentUsers);
			trace("lobbmanager----3");
			_lobby.addEventListener(LobbyEvent.CHATSEND,sendChat);
			_lobby.addEventListener(LobbyEvent.QUICKJOIN,quickJoin);
			_lobby.addEventListener(LobbyEvent.GETUSERINFO,getUserInfo);
			_lobby.addEventListener(LobbyEvent.GETMYINFO,getMyInfo );
			_lobby.addEventListener(LobbyEvent.ADDBUDDY,addBuddy );
			_lobby.addEventListener(LobbyEvent.REMOVEBUDDY,removeBuddy);
			_lobby.addEventListener(LobbyEvent.SETUSERINFO,setMyInfo);
			_lobby.addEventListener(LobbyEvent.GAMESELECT,gameSelect);
			_lobby.addEventListener(LobbyEvent.JOINGAME,joinGame);
			_lobby.addEventListener(LobbyEvent.CREATEGAME, createGame);
			
			trace("lobbmanager----4");
		    _es.engine.addEventListener(MessageType.JoinRoomEvent.name,onJoinRoomEvent);
			_es.engine.addEventListener(MessageType.PublicMessageEvent.name, onPublicMessageEvent);
			_es.engine.addEventListener(MessageType.PrivateMessageEvent.name,onPrivateMessageEvent);
			//_es.engine.addEventListener(MessageType.UserVariableUpdateEvent.name, onUserVariableUpdateEvent);
			_es.engine.addEventListener(MessageType.PluginMessageEvent.name, onPluginMessageEvent);
			_es.engine.addEventListener(MessageType.FindGamesResponse.name, onFindGamesResponse);
			//_es.engine.addEventListener(MessageType.GenericErrorResponse, onGenericErrorResponsz);
			//_es.engine.addEventListener(MessageType.ConnectionClosedEvent, onConnectionClosedEvent);
			//_es.engine.addEventListener(MessageType.BuddyStatusUpdatedEvent, onBuddyStatusUpdatedEvent);
			_es.engine.addEventListener(MessageType.AddBuddiesResponse.name, onBuddyAdded);
			_es.engine.addEventListener(MessageType.CreateOrJoinGameResponse.name, onCreateOrJoinGameResponse);
			
			
			userListState = "currUser";
			
			if (_room != null) {
				//create the request
				var lrr:LeaveRoomRequest = new LeaveRoomRequest();
				lrr.roomId = _room.id;
				lrr.zoneId = _room.zoneId;
				
				//send it
				_es.engine.send(lrr);
			}
			
			var jrr:JoinRoomRequest = new JoinRoomRequest();
			jrr.roomName = "Lobby";
			jrr.zoneName = "LobbyZone";
			//send it
			_es.engine.send(jrr);
			
			_gameListRefreshTimer = new Timer(2000);
			_gameListRefreshTimer.start();
			_gameListRefreshTimer.addEventListener(TimerEvent.TIMER, onGameListRefreshTimer);
			
		}
		
		private function loadBuddies(e:Event){
			userListState = "buddyList";
			updateUserList();
		}
		
		private function loadCurrentUsers(e:Event){
			userListState = "currUser";
			updateUserList();
		}
		
		private function addBuddy(e:LobbyEvent){
			var esob:EsObject = new EsObject();
			esob.setString(LobbyPluginConstants.ACTION, LobbyPluginConstants.ADD_BUDDY);
			esob.setString(LobbyPluginConstants.MESSAGE,this._currentCheckUser);
			trace("add buddy message send "+esob);
			this.sendToLobbyManagerPlugin(esob);
		}
		
		private function removeBuddy(e:LobbyEvent){
			var esob:EsObject = new EsObject();
			esob.setString(LobbyPluginConstants.ACTION, LobbyPluginConstants.REMOVE_BUDDY);
			esob.setString(LobbyPluginConstants.MESSAGE,this._currentCheckUser);
			trace("remove buddy message send "+esob);
			this.sendToLobbyManagerPlugin(esob);
		}
		 
		
		private function onBuddyAdded(e:AddBuddiesResponse):void{
			trace("add a buddy"+e.buddiesAdded);
		}
		
		
		
		private function onJoinRoomEvent(e:JoinRoomEvent):void{
			var eventRoom:Room = _es.managerHelper.zoneManager.zoneById(e.zoneId).roomById(e.roomId);
			
			if (eventRoom.name == "Lobby") {
				//the room you joined
				_room = eventRoom;
				
				initUserInfo();
				initGameList();
				initUserList();
			}
			
		}
		
		
		
		private function initUserInfo(){
			_myUserManager = _es.managerHelper.userManager;
			_user = _myUserManager.me;
			trace("user now ===="+_user.userName);
			var esob:EsObject = new EsObject();
			esob.setString(LobbyPluginConstants.ACTION,LobbyPluginConstants.LOAD_USERINFO);
			esob.setString(LobbyPluginConstants.MESSAGE,_user.userName);
			sendToLobbyManagerPlugin(esob);
		}
		
		
		
		private function initGameList(){
			var esob:EsObject = new EsObject();
			esob.setString(LobbyPluginConstants.ACTION,LobbyPluginConstants.LOAD_GAMES);
			
			sendToLobbyManagerPlugin(esob);
		}
		
		
		
		private function initUserList(){
			var esob:EsObject = new EsObject();
			esob.setString(LobbyPluginConstants.ACTION,LobbyPluginConstants.LOAD_BUDDIES);
			
			sendToLobbyManagerPlugin(esob);
		}
		
		
		
		private function updateUserList(){
			if(userListState == "currUser"){
				var users:Array = _room.users;
				
				var dp:DataProvider = new DataProvider();
				
				for (var i:int = 0; i < users.length;++i) {
					var user:User = users[i];
					dp.addItem( { label:user.userName, data:user.userName} );
					trace("add one item to userlist");
				}
				
				//与lobby沟通
				_lobby.setUserList(dp);
				
			}else if(userListState == "buddyList"){
				var users1:EsObject = _buddyList;
				trace(users1);
				var dp1:DataProvider = new DataProvider();
				
				if(users1 != null){
				for (var j:int = 0; j < users1.getEsObjectArray("results").length;++j) {
					var buddyname:String = _buddyList.getEsObjectArray("results")[j].getString("buddy");
					dp1.addItem( { label:buddyname, data:buddyname} );
				}
				
				}
				//与lobby沟通
				_lobby.setUserList(dp1);
				
		
			}
		}
		
		
		private function showGameList(s:Array) {
			trace("shwogamelist");
			
			var dp:DataProvider = new DataProvider();
			if(s!=null){
				for(var i:int = 0; i<s.length; i++){
					dp.addItem({label:s[i], data:s[i]});
				}
			}
			_lobby.setGameList(dp);
		}
		
		private function showRoomList(games:Array){
			trace("num of game:"+games.length);
			
			var dp:DataProvider = new DataProvider();
			for (var i:int = 0; i < games.length;++i) {	
				var game:ServerGame = games[i];
				var gameState:String = new String();
				var peopleNum:String = new String();
				var gameid:int = game.id;
				var roomName:String = game.gameDetails.getString("roomName");
				if(game.passwordProtected){
					gameState = "有密码";
				}else{
					gameState = "没有密码";
				}
				if(game.locked){
					peopleNum = "人数已满";
				}else{
					peopleNum = "人数未满";
				}
				var param:Array = new Array();
				param[0] = gameid;
				param[1] = game.passwordProtected;
				//dp.addItem({GameID:gameid, RoomName: roomName, GameState:gameState, PeopleNumber:peopleNum });
				dp.addItem( { label:gameid+"                                              "+roomName+"                                                  "+gameState+"                                              "+peopleNum, data:param} );
				 
				
			}
			if(dp!= null){
			trace("get room list:"+dp.toString());
			}
			_lobby.setRoomList(dp);
			
		}
		
		
		
		private function sendToLobbyManagerPlugin(esob:EsObject):void{
			var pr:PluginRequest = new PluginRequest();
			pr.pluginName = "LobbyManagerPlugin";
			pr.parameters = esob;
			pr.roomId = _room.id;
			pr.zoneId = _room.zoneId;
			
			_es.engine.send(pr);
		}
		
		
		
		private function getUserInfo(e:LobbyEvent):void{
			var esob:EsObject = new EsObject();
			esob.setString(LobbyPluginConstants.ACTION,LobbyPluginConstants.LOAD_USERINFO);
			esob.setString(LobbyPluginConstants.MESSAGE,String(e.param));
			this._currentCheckUser = String(e.param);
			
			sendToLobbyManagerPlugin(esob);
		}
		
		
		
		private function setMyInfo(e:LobbyEvent):void{
			var esob:EsObject = new EsObject();
			
			var param:EsObject = new EsObject();
			param.setString("username",e.param[0]);
			param.setInteger("gender" , e.param[1]);
			param.setString("state",e.param[2]);
			
			esob.setString(LobbyPluginConstants.ACTION, LobbyPluginConstants.SET_USERINFO);
			esob.setEsObject(LobbyPluginConstants.MESSAGE, param);
			
			sendToLobbyManagerPlugin(esob);
		}
		
		
		
		private function getMyInfo(e:LobbyEvent):void{
			showUserInfoPanel(_myInfo);
		}
		
		/*
		//添加好友列表
		private function handleLoadBuddies(esob:EsObject):void{
			//var users:Array = esob.getUsers();
			//--------------添加好友列表------------------------
			var dp:DataProvider = new DataProvider();
			
			for (var i:int = 0; i < users.length;++i) {
				var username:String = users[i].userName;
				dp.addItem( { label:user.userName, data:username} );
			}
			
			//与lobby沟通
			_userList.dataProvider = dp;
		}
		*/
		private function showUserInfoPanel(info:EsObject){
			var userinfo:Array = new Array();
			trace("show User info"+info);
			if(info != null){
			userinfo[0] = info.getEsObjectArray("results")[0].getString("username");
			userinfo[1] = info.getEsObjectArray("results")[0].getInteger("gender");
			trace(userinfo[1]);
			userinfo[2] = info.getEsObjectArray("results")[0].getString("state");
			var isme:Boolean = false;
			var isbuddy:Boolean = false;
			if(info == _myInfo){
				isme = true;
			}
			for (var j:int = 0; j < this._buddyList.getEsObjectArray("results").length;++j) {
				var buddyname:String = _buddyList.getEsObjectArray("results")[j].getString("buddy");
				if(buddyname == userinfo[0]){
					isbuddy = true;
				}
			}
			trace("showuserinfo is buddy "+isbuddy);
			_lobby.showUserInfoPanle(userinfo,isme,isbuddy);
			}
		}
		
		
		
		private function sendChat(e:LobbyEvent):void {
			
			trace(e.param);
			if (e.param.length > 0) {
				
				var msg:String = String(e.param);
				
				if (msg.charAt(0) == "/" && msg.indexOf(":") != -1) {
					
					var to:String = msg.substr(1, msg.indexOf(":") - 1);
					msg = msg.substr(msg.indexOf(":")+2);
					
					var prmr:PrivateMessageRequest = new PrivateMessageRequest();
					prmr.userNames = [to];
					prmr.message = msg;
					
					_es.engine.send(prmr);
					
				} else {
					
					var pmr:PublicMessageRequest = new PublicMessageRequest();
					pmr.message = String(e.param);
					pmr.roomId = _room.id;
					pmr.zoneId = _room.zoneId;
					
					_es.engine.send(pmr);
				}
				
				_lobby.setChatInput("");
			}
		}
		
		
		private function gameSelect(e:LobbyEvent):void{
			_currentSelectGame = String(e.param);
			gameListRefresh();
		}
		
		private function onGameListRefreshTimer(e:Event):void{
			if(_currentSelectGame == null){
				return;
			}
			gameListRefresh();
		}
		
		private function gameListRefresh(){
			
			var fgr:FindGamesRequest = new FindGamesRequest();
			
			//create search criteria that will filter the game list
			var criteria:SearchCriteria = new SearchCriteria();
			criteria.gameType = _currentSelectGame;
			trace("current game:"+_currentSelectGame);
			criteria.gameId = -1;
			
			//add the search criteria to the request
			fgr.searchCriteria = criteria;
			
			//send it
			_es.engine.send(fgr);
		}
		
		private function onFindGamesResponse(e:FindGamesResponse){
			showRoomList(e.games);
		}
		
		
		private function onPluginMessageEvent(event:PluginMessageEvent):void{
			var esob:EsObject = event.parameters;
			trace("onpluginmessageEvent");
			trace(esob);
			var action:String = esob.getString(LobbyPluginConstants.ACTION);
			switch (action) {
				case LobbyPluginConstants.LOAD_BUDDIES:
				    trace("loadbuddies:"+esob.getString(LobbyPluginConstants.STATE));
					
					_buddyList = esob.getEsObject(LobbyPluginConstants.MESSAGE);
					updateUserList();
					break;
				case LobbyPluginConstants.LOAD_USERINFO:
					trace("load userinfo:"+esob.getString(LobbyPluginConstants.STATE));
					
					var _userInfo:EsObject = esob.getEsObject(LobbyPluginConstants.MESSAGE);
					if(_userInfo.getEsObjectArray("results")[0].getString("username") == _user.userName){
						_myInfo = _userInfo;
					}else{
					trace("loadMyinfo"+_userInfo);
					this.showUserInfoPanel(_userInfo);
					}
					break;
				case LobbyPluginConstants.ADD_BUDDY:
					trace("add buddies:"+esob.getString(LobbyPluginConstants.STATE));
					
					if(esob.getString(LobbyPluginConstants.STATE) == LobbyPluginConstants.SUCCESS){
						_lobby.showMessagePanel("好友添加成功");
						this.initUserList();
						//trace();
					}else if(esob.getString(LobbyPluginConstants.STATE) == LobbyPluginConstants.FAILED){
						_lobby.showMessagePanel("好友添加失败");
					}
					break;
				case LobbyPluginConstants.REMOVE_BUDDY:
					trace("remove buddy"+esob.getString(LobbyPluginConstants.STATE));
					
					if(esob.getString(LobbyPluginConstants.STATE) == LobbyPluginConstants.SUCCESS){
						_lobby.showMessagePanel("好友移除成功");
						this.initUserList();
						//trace();
					}else if(esob.getString(LobbyPluginConstants.STATE) == LobbyPluginConstants.FAILED){
						_lobby.showMessagePanel("好友移除失败");
					}
					break;
				case LobbyPluginConstants.SET_USERINFO:
					trace("set userinfo"+esob.getString(LobbyPluginConstants.STATE));
					
					if(esob.getString(LobbyPluginConstants.STATE) == LobbyPluginConstants.SUCCESS){
						_lobby.showMessagePanel("信息修改成功");
						this.initUserInfo();
						//trace();
					}else if(esob.getString(LobbyPluginConstants.STATE) == LobbyPluginConstants.FAILED){
						_lobby.showMessagePanel("信息修改失败");
					}
					break;
				case LobbyPluginConstants.LOAD_GAMES:
					trace("load game list");
					
					var gameList:Array = esob.getStringArray(LobbyPluginConstants.MESSAGE);
					showGameList(gameList);
					
					
			}
		}
		
		private function onPublicMessageEvent(event:PublicMessageEvent):void{
			_lobby.addChat(event.userName+":"+event.message);
		}
		
		private function onPrivateMessageEvent(event:PrivateMessageEvent):void{
			_lobby.addChat("[private] "+event.userName+":"+event.message);
		}
		
		private function onCreateOrJoinGameResponse(event:CreateOrJoinGameResponse):void{
			trace("create game response:room id:" +event.roomId+"game id:" + event.gameId);
			trace("create game response:room name:"+event.gameDetails);
			trace( "create game");
			if(event.successful){
			_gameRoom = new Room();
			_gameRoom.id = event.roomId;
			_gameRoom.zoneId = event.zoneId;
			var e:LobbyEvent = new LobbyEvent(LobbyEvent.STARTGAME);
			e.param = this._currentSelectGame;
			dispatchEvent(e);
			}else{
				trace("crreate game response erroe:"+event.error.name);
				this._lobby.showMessagePanel(event.error.name);
			}
		}
		
		private function joinGame(event:LobbyEvent):void{
			var jgr:JoinGameRequest = new JoinGameRequest();
			trace("send join game request,gameid :"+event.param[0]);
			jgr.gameId = int(event.param[0]);
			if(event.param[1] != null){
				jgr.password = event.param[1] as String;
			}
			_es.engine.send(jgr);
		}
		
		private function createGame(event:LobbyEvent):void{
			var qjr:QuickJoinGameRequest = new QuickJoinGameRequest();
			trace("create game ---- game tyep:"+_currentSelectGame);
			qjr.gameType = this._currentSelectGame;
			qjr.zoneName = this._currentSelectGame;
			qjr.createOnly = true;
			var gamedetails:EsObject = new EsObject();
			gamedetails.setString("roomName", event.param[0]);
			qjr.gameDetails = gamedetails;
			trace("create game ----roomname:"+ gamedetails);
			trace("create game ----password:"+ event.param[1]);
			if(event.param[1]!= ""){
				qjr.password = event.param[1];
			}
			_es.engine.send(qjr);
		}
		
		private function quickJoin(event:LobbyEvent):void{
			var qjr:QuickJoinGameRequest = new QuickJoinGameRequest();
			qjr.gameType = this._currentSelectGame;
			qjr.zoneName = this._currentSelectGame;
			qjr.createOnly = false;
			_es.engine.send(qjr);
		}
		
		public function set lobby(l:Object):void{
			_lobby = l;
		}
		
		public function set es(es:ElectroServer):void{
			_es = es;
		}
		
		
		public function destroy(){
			_lobby.destroy();
			
			trace("send leave room request");
			var lrr:LeaveRoomRequest = new LeaveRoomRequest();
			lrr.roomId = _room.id;
			lrr.zoneId = _room.zoneId;
			_es.engine.send(lrr);
			
			_lobby.removeEventListener(LobbyEvent.BUDDYLIST,loadBuddies);
			_lobby.removeEventListener(LobbyEvent.CURRENTLIST,loadCurrentUsers);
			_lobby.removeEventListener(LobbyEvent.CHATSEND,sendChat);
			_lobby.removeEventListener(LobbyEvent.QUICKJOIN,quickJoin);
			_lobby.removeEventListener(LobbyEvent.GETUSERINFO,getUserInfo);
			_lobby.removeEventListener(LobbyEvent.GETMYINFO,getMyInfo );
			_lobby.removeEventListener(LobbyEvent.ADDBUDDY,addBuddy );
			_lobby.removeEventListener(LobbyEvent.REMOVEBUDDY,removeBuddy);
			_lobby.removeEventListener(LobbyEvent.SETUSERINFO,setMyInfo);
			_lobby.removeEventListener(LobbyEvent.GAMESELECT,gameSelect);
			_lobby.removeEventListener(LobbyEvent.JOINGAME,joinGame);
			_lobby.removeEventListener(LobbyEvent.CREATEGAME, createGame);
			
			_es.engine.removeEventListener(MessageType.JoinRoomEvent.name,onJoinRoomEvent);
			_es.engine.removeEventListener(MessageType.PublicMessageEvent.name, onPublicMessageEvent);
			_es.engine.removeEventListener(MessageType.PrivateMessageEvent.name,onPrivateMessageEvent);
			//_es.engine.addEventListener(MessageType.UserVariableUpdateEvent.name, onUserVariableUpdateEvent);
			_es.engine.removeEventListener(MessageType.PluginMessageEvent.name, onPluginMessageEvent);
			_es.engine.removeEventListener(MessageType.FindGamesResponse.name, onFindGamesResponse);
			//_es.engine.addEventListener(MessageType.GenericErrorResponse, onGenericErrorResponsz);
			//_es.engine.addEventListener(MessageType.ConnectionClosedEvent, onConnectionClosedEvent);
			//_es.engine.addEventListener(MessageType.BuddyStatusUpdatedEvent, onBuddyStatusUpdatedEvent);
			_es.engine.removeEventListener(MessageType.AddBuddiesResponse.name, onBuddyAdded);
			_es.engine.removeEventListener(MessageType.CreateOrJoinGameResponse.name, onCreateOrJoinGameResponse);
			
			_gameListRefreshTimer.removeEventListener(TimerEvent.TIMER, onGameListRefreshTimer);
		}
	
	}
}